//
//  LocalRecordViewCtr.m
//  CCBbelefitLife
//
//  Created by liurg on 15/12/28.
//  Copyright © 2015年 liurg. All rights reserved.
//

#import "LocalRecordViewCtr.h"
#import "RecordViewCell.h"
#import "Utilities.h"
#import "ProgressBarView.h"
#import "QNUploadOption.h"
#import "QNUploadManager.h"

@interface LocalRecordViewCtr()<UITableViewDataSource , UITableViewDelegate,RecordViewCellDelegate,UIActionSheetDelegate>{
    
    UITableView * _chatTableView;
    UIView   *maskView;
    NSIndexPath * index;
    UIActionSheet *asheet;//操作表
    NSTimer * timer;
    UILabel * resultLabel;
    int resultCount;
}

@property(nonatomic,retain) NSMutableArray *dataArray;
@property(nonatomic,retain) NSArray *fileNameList;
@property(nonatomic,assign) NSInteger lastPlayIndex;
@property(nonatomic,assign) BOOL isPlay;
@property(nonatomic,retain) AVAudioPlayer *audioPlayRec;
@property(nonatomic,retain) NSTimer *showPlayTimer;
@property(nonatomic,retain) UILabel *startTimeLab;
@property(nonatomic,retain) UIView * myview;
@property(nonatomic,retain) ProgressBarView *progressBarView;
@property (nonatomic) UILabel *processLabel;

@end

@implementation LocalRecordViewCtr


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"本地录音";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupView];
    [self configData];
    
    // 判断进去的模式
    if (self.recordMusicPath==NULL)
    {
    }
    else
    {   //保存录音时的阴影界面
        self.myview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth, mainScreenHeight)];
        [self.myview setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.368f]];
        [self.view addSubview:self.myview];
        [self initProcessBarView];
    }
    
}

- ( void ) viewWillAppear:( BOOL ) animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    self.tabBarController.tabBar.hidden = YES;
    // [ShareAppDelegate.ApptabBar hideSysTabar];
    [self buildNavView];
}

//正在保存的圆形进度条
- (void)initProcessBarView {
    self.progressBarView = [[ProgressBarView alloc]initWithFrame:CGRectMake(mainScreenWidth/5*2, mainScreenWidth/5*2, mainScreenWidth/5,mainScreenWidth/5)];
    [self.progressBarView setBackgroundColor:[UIColor clearColor]];
    self.progressBarView.delegate = self;
    self.progressBarView.progressBarColor = [UIColor orangeColor];
    self.progressBarView.progressBarShadowOpacity = .1f;
    self.progressBarView.progressBarArcWidth = 2.0f;
    self.progressBarView.wrapperColor = [UIColor colorWithRed: 240.0 / 255.0 green:240.0 / 255.0 blue: 240.0 / 255.0 alpha: .5];
    self.progressBarView.duration = 1.0f;//运行的时间
    [self.view addSubview: self.progressBarView];
    [self.progressBarView run: 0.0f];
    //label
    NSInteger labelWidth = 100;
    NSInteger labelHeight = 20;
    self.processLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.progressBarView.frame.size.width - labelWidth) / 2, (self.progressBarView.frame.size.height - labelHeight) * 1.5, labelWidth, labelHeight)];
    self.processLabel.text = @"0%";
    self.processLabel.numberOfLines = 1;
    self.processLabel.textAlignment = NSTextAlignmentRight;
    self.processLabel.font = [self.processLabel.font fontWithSize:14];
    self.processLabel.textColor = [UIColor whiteColor];
    [self.progressBarView addSubview: self.processLabel];
}

#pragma mark--progressBarView代理方法
- (void)animationDidStop:(CAAnimation *)processAnimation finished:(BOOL)flag {
    NSString *stringFloat = [NSString stringWithFormat:@"%f", round(self.progressBarView.currentProgress * 100)];
    NSInteger stringInt=[stringFloat intValue];
    //NSLog(@"current at %ld", (long)stringInt);
    if (self.progressBarView.currentProgress < 1.0)
    {
        self.processLabel.text = [NSString stringWithFormat:@"正在保存%ld%@", (long)stringInt, @"%.."];
        [self.progressBarView run:self.progressBarView.currentProgress];
    }
    else if (self.progressBarView.currentProgress > 1)
    {
        [self.progressBarView removeFromSuperview];
        [self.myview removeFromSuperview];
        [_chatTableView reloadData];
    }
}

-(void)setupView{
    
    self.view.backgroundColor = [UIColor blackColor];
    _chatTableView = [[UITableView alloc] initWithFrame:CGRectMake( 0.0 , 0 , mainScreenWidth , self.view.height - 64  ) style:UITableViewStylePlain];
    _chatTableView.backgroundColor = JYColor(246, 246, 246);
    _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // _chatTableView.allowsSelection = NO;
    _chatTableView.dataSource = self;
    _chatTableView.delegate = self;
    [self.view addSubview:_chatTableView];
    
    resultLabel = [[UILabel alloc]initWithFrame:CGRectMake((mainScreenWidth-100)/2, (mainScreenHeight-40)/2, 100, 40)];
    resultLabel.hidden = YES;
    resultLabel.backgroundColor = JYColor(245, 219, 180);
    resultLabel.textColor = [UIColor redColor];
    [resultLabel setTextAlignment:(NSTextAlignmentCenter)];
    resultLabel.layer.borderColor = [UIColor blackColor].CGColor;
    resultLabel.layer.borderWidth = 1.0;
    resultLabel.layer.cornerRadius = 5.0;
    [self.view addSubview:resultLabel];
}

-(void)buildNavView{
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back.png" highIcon:@"back.png" target:self action:@selector(backBtnAction)];
    
}

-(void)backBtnAction{
    
    [_audioPlayRec stop];
    _audioPlayRec = nil;
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}


-(void)configData{
    _lastPlayIndex = -1;
    _isPlay = NO;
    
    NSString *path =[NSString stringWithFormat:@"%@/Documents/docRecordPath/",NSHomeDirectory()];
    self.fileNameList=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    
    self.dataArray = [[NSMutableArray alloc]init];
    
    for (int i = 0 ; i<_fileNameList.count; i++)
    {
        NSString * fileStr = [_fileNameList objectAtIndex:i];
        if([fileStr hasSuffix:@".mp3"] && fileStr.length > 12){
            NSString *str=[[_fileNameList objectAtIndex:i] substringToIndex:12];
            NSString *recordTime=[NSString stringWithFormat:@"%@/%@/%@ %@:%@",
                                  [str substringWithRange:NSMakeRange(0, 4)],
                                  [str substringWithRange:NSMakeRange(4, 2)],
                                  [str substringWithRange:NSMakeRange(6, 2)],
                                  [str substringWithRange:NSMakeRange(8, 2)],
                                  [str substringWithRange:NSMakeRange(10,2)]];
            
            NSString *path =[NSString stringWithFormat:@"%@/Documents/docRecordPath/",NSHomeDirectory()];
            NSString *file = [_fileNameList objectAtIndex:i];
            NSString * filename = [path stringByAppendingString:file];
            NSURL *fileUrl = [NSURL fileURLWithPath:filename];
            AVAudioPlayer *thePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
            NSString * endTime;
            int m = thePlayer.duration / 60;
            int s = ((int) thePlayer.duration+1) % 60;
            endTime = [NSString stringWithFormat:@"%.2d:%.2d", m, s];
            NSLog(@"%f",thePlayer.duration);
            NSLog(@"%@",endTime);
            thePlayer = nil;
            NSString * cc = [_fileNameList objectAtIndex:i];
            NSString * dd = [cc substringWithRange:NSMakeRange(0, cc.length-4)];
            [self.dataArray addObject:@{@"recordName":dd,@"recordTime":recordTime,@"startTime":@"00:00",@"endTime":endTime}];
        }
    }
}

-(void)showTime:(NSTimer *)timer{
    //动态更新进度条时间
    if (_audioPlayRec == nil||!_isPlay) {
        return ;
    }
    if ((int)_audioPlayRec.currentTime % 60 < 10) {
        _startTimeLab.text = [NSString stringWithFormat:@"0%d:0%d",(int)_audioPlayRec.currentTime / 60, (int)_audioPlayRec.currentTime % 60];
    } else {
        _startTimeLab.text = [NSString stringWithFormat:@"%d:%d",(int)_audioPlayRec.currentTime / 60, (int)_audioPlayRec.currentTime % 60];
    }
    UITableViewCell *cell = [_chatTableView cellForRowAtIndexPath:index];
    ((RecordViewCell *)cell).progressSlider.value = _audioPlayRec.currentTime/_audioPlayRec.duration*((RecordViewCell *)cell).progressSlider.maximumValue;
    if (_audioPlayRec.duration < _audioPlayRec.currentTime+1) {
        double delayInSecond = 1.5;
        dispatch_time_t popTimeone = dispatch_time(DISPATCH_TIME_NOW, delayInSecond * NSEC_PER_SEC);
        dispatch_after(popTimeone, dispatch_get_main_queue(), ^(void){
            [_audioPlayRec pause];
            _isPlay = NO;
            
        });
        
    }
}

-(void)playVoice{
    
    if (_lastPlayIndex!=-1) {
        if (_lastPlayIndex  == index.section) {
            //停止音乐,播放音乐
            if (!_isPlay) {
                [_audioPlayRec play];
                _isPlay = YES;
            }
            else{
                [_audioPlayRec pause];
                _isPlay = NO;
            }
        }
        else{
            _lastPlayIndex = index.section;
            [self playMusic];
        }
    }
    else{
        _lastPlayIndex = index.section;
        [self playMusic];
    }
    
}

- (void)progressStart{
}

-(void)playMusic{
    NSString *path =[NSString stringWithFormat:@"%@/Documents/docRecordPath/",NSHomeDirectory()];
    NSString *file = self.fileNameList[index.section];
    NSString * filename = [path stringByAppendingString:file];
    NSRange range = {file.length-5,1};
    NSString * SeleteStyle  = [file substringWithRange:range];
    
    NSURL *fileUrl = [NSURL fileURLWithPath:filename];
    AVAudioPlayer *thePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
    thePlayer.volume = 1;
    //创建播放器
    _audioPlayRec = thePlayer; //赋值给自己定义的类变量
    [_audioPlayRec prepareToPlay];
    [_audioPlayRec setVolume:1]; //设置音量大小
    _audioPlayRec.numberOfLoops = -1;//设置音乐播放次数 -1为一直循环 ，将音频播放器的numberOfLoops属性设为负数使得播放无限循环
    NSLog(@"%f seconds played so far", _audioPlayRec.currentTime); //查看播放的初始时间，也就是从多少秒开始播放
    _audioPlayRec.currentTime = 1; // jump to the 10 second mark //设置播放开始的时间
    [_audioPlayRec play]; //播放
    _isPlay = YES;
    _showPlayTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f
                                                      target:self
                                                    selector:@selector(showTime:)
                                                    userInfo:nil
                                                     repeats:YES];
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return self.dataArray.count;
    // return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RecordViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecordViewCell"];
    // Configure the cell...
    if ( cell == nil ) {
        cell = [[RecordViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RecordViewCell"];
        cell.delegate =self;
    }
    [cell updateCellWithNewData:[self.dataArray objectAtIndex:indexPath.section]];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 100;
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewRowAction *layTopRowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@" 删除 " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSString *path =[NSString stringWithFormat:@"%@/Documents/docRecordPath/",NSHomeDirectory()];
        NSString *file = self.fileNameList[indexPath.section];
        NSString * filename = [path stringByAppendingString:file];
        [[NSFileManager defaultManager]removeItemAtPath:filename error:nil];
        [self.dataArray removeObjectAtIndex:indexPath.section];
        [_chatTableView reloadData];
        
    }];
    layTopRowAction1.backgroundColor = [UIColor redColor];
    NSArray *arr = @[layTopRowAction1];
    return arr;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSLog(@"tableview.frame = %@",NSStringFromCGRect(_chatTableView.frame));
    //
    //
    //    maskView = [[UIView alloc]initWithFrame:CGRectMake(50, 250, 200, 300)];
    //    maskView.backgroundColor = [UIColor redColor];
    //    [_chatTableView addSubview:maskView];
    //    UIButton *yeBtn = [[UIButton alloc ]initWithFrame:CGRectMake(20, 20, 150, 150)];
    //    [maskView addSubview:yeBtn];
    //    yeBtn.backgroundColor = [UIColor yellowColor];
    //    [yeBtn addTarget:self action:@selector(testAction) forControlEvents:UIControlEventTouchUpInside];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForhearderInSection:(NSInteger)section
{
    UIView * aView = [[UIView alloc] initWithFrame:CGRectMake( 0.0 , 0.0 , mainScreenWidth , 10 )];
    aView.backgroundColor = JYColor(246, 246, 246);
    return aView;
}


#pragma mark -  RecordViewCellDelegate

-(void)playRecordVoice:(UIButton *)playRecordBtn{
    
    UIView *view = [playRecordBtn superview];
    UITableViewCell *cell = (UITableViewCell *)[view superview];//获取cell
    _startTimeLab = (UILabel*)[cell viewWithTag:104];
    NSIndexPath *indexPathPlay = [_chatTableView indexPathForCell:cell];//获取cell对应
    index = indexPathPlay;
    [self playVoice];
}
-(void)shareMusic:(UIButton *)shareBtn{
    UIView *view = [shareBtn superview];
    UITableViewCell *cell = (UITableViewCell *)[view superview];//获取cell
    NSIndexPath *indexPathPlay = [_chatTableView indexPathForCell:cell];//获取
    index = indexPathPlay;
    asheet=[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"公开上传到我的主页",@"以此录音发起合唱",nil];
    [asheet showInView:self.view];
}

//播放进度条拖动
-(void)playProgressChange:(UISlider *)progressSlider{
    _audioPlayRec.currentTime = progressSlider.value/progressSlider.maximumValue * _audioPlayRec.duration;
    
}

#pragma mark -  UIActionSheetDelegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0){
        [self shareFileToQiNiu];
    }else if (buttonIndex == 1){
        
    }
}

- (void)shareFileToQiNiu{
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:@"/api/qiniu/get-upload-token"];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //    创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSDictionary * bodyDict = [dic objectForKey:@"body"];
        NSString * key1 = [bodyDict objectForKey:@"key"];
        NSString * Btoken = [bodyDict objectForKey:@"token"];
        NSString *path =[NSString stringWithFormat:@"%@/Documents/docRecordPath/",NSHomeDirectory()];
        NSString *file = self.fileNameList[index.section];
        NSString * filename = [path stringByAppendingString:file];
        QNUploadManager * QNManager = [[QNUploadManager alloc]init];
        [QNManager putFile:filename key:key1 token:Btoken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            
            NSString *inURL = [MyBaseUrl stringByAppendingString:@"/api/records"];
            
            NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
            
            //    创建请求
            manager.requestSerializer =[AFHTTPRequestSerializer serializer];
            
            [manager.requestSerializer setValue:@"application/json"
                             forHTTPHeaderField:@"Accept"];
            [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                             forHTTPHeaderField:@"Authorization"];
            
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            NSString * str = [NSString stringWithFormat:@"http://7xp1hi.com2.z0.glb.qiniucdn.com/%@",key];
            NSDictionary * dataDict = @{@"id":@"0",@"type":@"mp3",@"songId":@"172",@"description":@"稳稳的幸福歌曲描述",@"url":str,@"name":@"朋友",@"userId":@"10009"};
            [manager GET:inURL parameters:dataDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
                NSString * resultCode  = [dict objectForKey:@"resultCode"];
                resultCount = 0;
                timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(SuccessResult) userInfo:nil repeats:YES];
                _chatTableView.alpha = 0.5;
                resultLabel.hidden = NO;
                if([resultCode isEqualToString:@"SUCCESS"]){
                    resultLabel.text = @"分享成功";
                }else{
                    resultLabel.text = @"分享失败";
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error){
                
                
            }];
        } option:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

-(void)SuccessResult{
    resultCount++;
    if(resultCount == 3){
        _chatTableView.alpha = 1.0;
        [timer invalidate];
        timer = nil;
        resultLabel.hidden = YES;
    }
}

@end
